import styles from './index.module.less';
import { useRef } from 'react';
import { Button, message, Tooltip } from 'antd';
import { useEffect, useState } from 'react';
import { lunXunTimeKuai, positionNums } from '@/utils/helper';
import { ProTable, ProColumns } from '@ant-design/pro-components';
import { contractApi, positionsApi, submitOrderApi } from '@/api';
import { formatNum, getUsdtNum, isLocal, isSuccess, numNoSiWu, orderText } from '@/utils';
import JianCangModal from './JianCangModal';
import { useInterval } from 'ahooks';
import PositionType from './PositionType';
import ZhiYingModal from './ZhiYingModal';
import ZhiYingBuFenModal from './ZhiYingBuFenModal';
import { ZhiYingDom } from './ZhiYingSunCpn';
import { YSXYingKui } from './CommonCpn';
import PubSub from 'pubsub-js';

let isFirst = true;
export default function Position({ tableWidth }: any) {
  const tableRef: any = useRef('');
  const [open, setOpen] = useState(false);
  const [formData, setFormData] = useState({});
  const [contractList, setContractList] = useState<any>(null);
  const [list, setList] = useState<any>([]);
  const [openZhiYing, setOpenZhiYing] = useState(false);
  const [openBuFenZhiYing, setOpenBuFenZhiYing] = useState(false);
  const [loading, setLoading] = useState(false);
  const [loadingPingCang, setLoadingPingCang] = useState(false);

  useEffect(() => {
    isFirst = true;
    getData();
  }, []);

  // 轮询
  useInterval(() => {
    getData();
  }, lunXunTimeKuai);

  useEffect(() => {
    if (!contractList) return;
    const _list = list.map((item: any) => ({
      ...item,
      ...positionNums(item, contractList),
    }));
    setList(_list);
  }, [contractList]);

  // 请求
  const getData = async () => {
    setLoading(true);
    const res: any = await positionsApi({});
    isFirst = false;
    setLoading(false);
    if (!isSuccess(res)) return;
    const list = res?.data.map((e: any) => {
      e.newSize = e?.size * e?.userDirection;
      return e;
    });
    console.log('res: 仓位', list[0]);
    const positionData = list[0];
    const baoZhengJin = positionData?.baoZhengJin;
    const weiShiXianYingKui = positionData?.weiShiXianYingKui?.num;
    const yiShiXianYingKui = positionData?.ysxYingKui?.pnl;
    console.log('仓位页', -baoZhengJin, weiShiXianYingKui, yiShiXianYingKui);
    setList(list);
    getContracts(res?.data.map((item: any) => item?.contract));
  };

  // 减仓dom
  const JianCangDom = ({ num }: any) => (
    <div className={styles.jianCangWrap}>
      {[1, 2, 3, 4, 5].map((item: any, i: number) => (
        <div className={`${styles.jitem} ${num >= item && styles.jitemAct}`} key={i}></div>
      ))}
    </div>
  );

  const columns: ProColumns[] = [
    {
      title: '合约',
      dataIndex: 'serveName',
      render: (text: any, record: any) => <PositionType record={record} />,
    },
    {
      title: '数量',
      dataIndex: 'size',
      render: (text: any, record: any) => (
        <div>
          <Tooltip
            title={
              <>
                <div>持仓张数: {text} 张</div>
                <div>
                  持仓币数: {text * record?.contractInfo?.quanto_multiplier}{' '}
                  {record?.contract.split('_')[0]}
                </div>
              </>
            }
          >
            {getUsdtNum(record)} USDT
          </Tooltip>
        </div>
      ),
    },
    {
      title: '开仓均价',
      dataIndex: 'entry_price',
      render: (text: any, record: any) => <>{formatNum(text)}</>,
    },
    {
      title: '标记价格',
      dataIndex: 'jjj',
      render: (text: any, record: any) => (
        <>{contractList && formatNum(contractList[record?.contract]?.index_price)}</>
      ),
    },
    {
      title: '预估强平价',
      hideInTable: true,
      dataIndex: 'qingPingJia',
    },
    // {
    //   title: '盈亏平衡价',
    //   dataIndex: 'serveName',
    // },
    {
      title: '保证金',
      dataIndex: 'baoZhengJin',
      render: (text: any, record: any) => <>{numNoSiWu(text)} USDT</>,
    },
    // {
    //   title: '保证金率(MMR)',
    //   dataIndex: 'serveName',
    // },
    {
      title: '未实现盈亏(回报率)',
      dataIndex: 'unrealised_pnl',
      render: (text: any, record: any) => (
        <p
          key="bzj"
          className={`${record?.weiShiXianYingKui?.num > 0 ? 'color-red' : 'color-green'}`}
        >
          {record?.weiShiXianYingKui?.num?.toFixed(2)} USDT (
          {(record?.weiShiXianYingKui?.huiBaoLv * 100)?.toFixed(2)}%)
        </p>
      ),
    },
    YSXYingKui(),
    {
      title: '仓位止盈/止损',
      dataIndex: 'serveName',
      render: (text: any, record: any) => (
        <ZhiYingDom
          record={record}
          type="all"
          zhiYingDomClick={() => zhiYingDomClick('all', record)}
        />
      ),
    },
    {
      title: '部分仓位止盈/止损',
      dataIndex: 'serveName',
      render: (text: any, record: any) => (
        <ZhiYingDom
          record={record}
          type="bufen"
          zhiYingDomClick={() => zhiYingDomClick('bufen', record)}
        />
      ),
    },
    // {
    //   title: () => <ThTip title="追踪止盈" tip="xxxx" />,
    //   dataIndex: 'serveName',
    // },
    // {
    //   title: () => <ThTip title="MMR止损" tip="xxxx" />,
    //   dataIndex: 'serveName',
    // },
    {
      title: '自动减仓', // 5最低
      dataIndex: 'adl_ranking',
      render: (text: any, record: any) => [<JianCangDom num={6 - text} key="jc" />],
    },
    // {
    //   title: () => <ThTip title="反手" tip="xxxx" />,
    //   dataIndex: 'serveName',
    // },
    {
      title: '减仓/平仓',
      fixed: 'right',
      dataIndex: 'option',
      width: 140,
      render: (_: any, record: any) => [
        <div key="opt" style={{ marginLeft: -8 }}>
          <Button type="link" size="small" onClick={() => openModal({ type: 'xian', ...record })}>
            限价
          </Button>
          <Button type="link" size="small" onClick={() => openModal({ type: 'shijia', ...record })}>
            市价
          </Button>
        </div>,
      ],
    },
  ];

  // 打开弹框
  function openModal(data: any = {}) {
    setOpen(true);
    setFormData(data);
  }

  // 打开止盈弹框
  function openZhiYingModal(data: any = {}) {
    setOpenZhiYing(true);
    setFormData(data);
  }

  // 打开止盈弹框
  function openBuFenZhiYingModal(data: any = {}) {
    setOpenBuFenZhiYing(true);
    setFormData(data);
  }

  // 所有合约
  async function getContracts(list: any) {
    const arr = list.map((item: any) => getContract(item));
    const res: any = await Promise.allSettled(arr);
    const _list = res
      .filter((item: any) => item?.status === 'fulfilled')
      .map((item: any) => item?.value);
    const obj: any = {};
    _list.forEach((item: any) => {
      obj[item?.name] = {
        ...item,
        quanto_multiplier: Number(item?.quanto_multiplier),
        taker_fee_rate: Number(item?.taker_fee_rate),
      };
    });
    setContractList(obj);
  }

  async function getContract(contract: any) {
    const res: any = await contractApi({ contract });
    return res?.data;
  }

  function zhiYingDomClick(type: any, record: any) {
    if (type === 'all') {
      openZhiYingModal(record);
    } else {
      openBuFenZhiYingModal(record);
    }
  }

  const reload = () => getData();

  async function yjPingCang() {
    setLoadingPingCang(true);
    const arr = list.map(async (item: any) => pingCang({ contract: item?.contract }));
    const res: any = await Promise.allSettled(arr);
    setLoadingPingCang(false);
    const resarr = res.map((item: any) => item?.value);
    // if (resarr.includes(false)) return;
    // message.success('成功');
    const isSuccess = resarr.every((item: any) => item.success);
    console.log('isSuccess: ', isSuccess);
    if (!isSuccess) {
      // 检测是否报双仓模式的错误
      const isShuangCangErr = resarr.some((item: any) =>
        item?.msg?.includes('close is not allowed in dual-mode'),
      );
      message.error(isShuangCangErr ? '请将双向持仓改为单向持仓，再平仓' : '平仓失败');
    } else {
      message.success('成功');
    }
    PubSub.publish('updataKeYongYuE', true);
    getData();
  }

  // 平仓
  async function pingCang(val: any) {
    let params: any = {
      contract: val?.contract,
      text: orderText,
      price: 0,
      size: 0,
      tif: 'ioc',
      close: true,
      stp_act: '-',
    };
    const res: any = await submitOrderApi(params);
    if (!isSuccess(res, false)) return { success: false, msg: res.msg };
    return { success: true, result: res };
  }

  return (
    <div className={styles.PositionCpn}>
      <br />
      {list?.length > 0 && (
        <div className={styles.positionTop}>
          <Button loading={loadingPingCang} shape="round" size="small" onClick={yjPingCang}>
            一键平仓
          </Button>
        </div>
      )}
      <ProTable
        rowKey="id"
        columns={columns}
        dataSource={list}
        actionRef={tableRef}
        search={false}
        options={false}
        scroll={{ x: isLocal() ? 900 : tableWidth }}
        pagination={false}
        loading={isFirst && loading}
      />
      {open && <JianCangModal open={open} setOpen={setOpen} formData={formData} reload={reload} />}
      {openZhiYing && (
        <ZhiYingModal
          open={openZhiYing}
          setOpen={setOpenZhiYing}
          formData={formData}
          reload={reload}
          contractList={contractList}
        />
      )}
      {openBuFenZhiYing && (
        <ZhiYingBuFenModal
          open={openBuFenZhiYing}
          setOpen={setOpenBuFenZhiYing}
          formData={formData}
          reload={reload}
          contractList={contractList}
        />
      )}
    </div>
  );
}
